import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { message } from 'antd'
import NproGress from 'nprogress'
import Cookie from 'js-cookie'
import whiteList from './whiteList'
import 'nprogress/nprogress.css'

interface IAuth {
    headers: {
        Authorization: string | undefined
    }
}

type AxiosAllConfig = IAuth | AxiosRequestConfig

const int: AxiosInstance = axios.create({
    timeout: 3000
})

int.interceptors.request.use((config: AxiosAllConfig) => {
    if (config.headers) {
        config.headers.Authorization = Cookie.get('token') ? Cookie.get('token') : ''
    }
    NproGress.start()
    return config
})

int.interceptors.response.use((data: AxiosResponse) => {
    NproGress.done()
    if (data.status === 200) {
        // 判断是否存在白名单中
        const isWhiteList = whiteList.some(item => item.method === data.config.method && data.config.url?.includes(item.url))
        if (isWhiteList) {
            if (data.data.message) {
                message.success(data.data.message)
            } else {
                message.success("请求成功")
            }
        }
    }
    return data.data
}, ((err: AxiosError) => {
    NproGress.done()
    if (err.response) {
        switch (err.response.status) {
            case 422:
                message.error('参数错误')
                break;
            case 401:
                message.error('没有权限')
                break;
        }
    }
}))


export default int

